package com.xjgzinfo.usdp.web.rest;

import com.xjgzinfo.usdp.AvueServer4jApp;
import com.xjgzinfo.usdp.config.TestSecurityConfiguration;
import com.xjgzinfo.usdp.domain.WebConfig;
import com.xjgzinfo.usdp.domain.AppClass;
import com.xjgzinfo.usdp.repository.WebConfigRepository;
import com.xjgzinfo.usdp.service.WebConfigService;
import com.xjgzinfo.usdp.service.dto.WebConfigDTO;
import com.xjgzinfo.usdp.service.mapper.WebConfigMapper;
import com.xjgzinfo.usdp.service.dto.WebConfigCriteria;
import com.xjgzinfo.usdp.service.WebConfigQueryService;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;
import javax.persistence.EntityManager;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

/**
 * Integration tests for the {@link WebConfigResource} REST controller.
 */
@SpringBootTest(classes = { AvueServer4jApp.class, TestSecurityConfiguration.class })
@AutoConfigureMockMvc
@WithMockUser
public class WebConfigResourceIT {

    private static final String DEFAULT_PACKAGES = "AAAAAAAAAA";
    private static final String UPDATED_PACKAGES = "BBBBBBBBBB";

    private static final String DEFAULT_ASSETS_TYPE = "AAAAAAAAAA";
    private static final String UPDATED_ASSETS_TYPE = "BBBBBBBBBB";

    private static final String DEFAULT_APP_SCHEMA = "AAAAAAAAAA";
    private static final String UPDATED_APP_SCHEMA = "BBBBBBBBBB";

    @Autowired
    private WebConfigRepository webConfigRepository;

    @Autowired
    private WebConfigMapper webConfigMapper;

    @Autowired
    private WebConfigService webConfigService;

    @Autowired
    private WebConfigQueryService webConfigQueryService;

    @Autowired
    private EntityManager em;

    @Autowired
    private MockMvc restWebConfigMockMvc;

    private WebConfig webConfig;

    /**
     * Create an entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static WebConfig createEntity(EntityManager em) {
        WebConfig webConfig = new WebConfig()
            .packages(DEFAULT_PACKAGES)
            .assetsType(DEFAULT_ASSETS_TYPE)
            .appSchema(DEFAULT_APP_SCHEMA);
        return webConfig;
    }
    /**
     * Create an updated entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static WebConfig createUpdatedEntity(EntityManager em) {
        WebConfig webConfig = new WebConfig()
            .packages(UPDATED_PACKAGES)
            .assetsType(UPDATED_ASSETS_TYPE)
            .appSchema(UPDATED_APP_SCHEMA);
        return webConfig;
    }

    @BeforeEach
    public void initTest() {
        webConfig = createEntity(em);
    }

    @Test
    @Transactional
    public void createWebConfig() throws Exception {
        int databaseSizeBeforeCreate = webConfigRepository.findAll().size();
        // Create the WebConfig
        WebConfigDTO webConfigDTO = webConfigMapper.toDto(webConfig);
        restWebConfigMockMvc.perform(post("/api/web-configs").with(csrf())
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(webConfigDTO)))
            .andExpect(status().isCreated());

        // Validate the WebConfig in the database
        List<WebConfig> webConfigList = webConfigRepository.findAll();
        assertThat(webConfigList).hasSize(databaseSizeBeforeCreate + 1);
        WebConfig testWebConfig = webConfigList.get(webConfigList.size() - 1);
        assertThat(testWebConfig.getPackages()).isEqualTo(DEFAULT_PACKAGES);
        assertThat(testWebConfig.getAssetsType()).isEqualTo(DEFAULT_ASSETS_TYPE);
        assertThat(testWebConfig.getAppSchema()).isEqualTo(DEFAULT_APP_SCHEMA);
    }

    @Test
    @Transactional
    public void createWebConfigWithExistingId() throws Exception {
        int databaseSizeBeforeCreate = webConfigRepository.findAll().size();

        // Create the WebConfig with an existing ID
        webConfig.setId(1L);
        WebConfigDTO webConfigDTO = webConfigMapper.toDto(webConfig);

        // An entity with an existing ID cannot be created, so this API call must fail
        restWebConfigMockMvc.perform(post("/api/web-configs").with(csrf())
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(webConfigDTO)))
            .andExpect(status().isBadRequest());

        // Validate the WebConfig in the database
        List<WebConfig> webConfigList = webConfigRepository.findAll();
        assertThat(webConfigList).hasSize(databaseSizeBeforeCreate);
    }


    @Test
    @Transactional
    public void checkAssetsTypeIsRequired() throws Exception {
        int databaseSizeBeforeTest = webConfigRepository.findAll().size();
        // set the field null
        webConfig.setAssetsType(null);

        // Create the WebConfig, which fails.
        WebConfigDTO webConfigDTO = webConfigMapper.toDto(webConfig);


        restWebConfigMockMvc.perform(post("/api/web-configs").with(csrf())
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(webConfigDTO)))
            .andExpect(status().isBadRequest());

        List<WebConfig> webConfigList = webConfigRepository.findAll();
        assertThat(webConfigList).hasSize(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    public void getAllWebConfigs() throws Exception {
        // Initialize the database
        webConfigRepository.saveAndFlush(webConfig);

        // Get all the webConfigList
        restWebConfigMockMvc.perform(get("/api/web-configs?sort=id,desc"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(webConfig.getId().intValue())))
            .andExpect(jsonPath("$.[*].packages").value(hasItem(DEFAULT_PACKAGES.toString())))
            .andExpect(jsonPath("$.[*].assetsType").value(hasItem(DEFAULT_ASSETS_TYPE)))
            .andExpect(jsonPath("$.[*].appSchema").value(hasItem(DEFAULT_APP_SCHEMA.toString())));
    }
    
    @Test
    @Transactional
    public void getWebConfig() throws Exception {
        // Initialize the database
        webConfigRepository.saveAndFlush(webConfig);

        // Get the webConfig
        restWebConfigMockMvc.perform(get("/api/web-configs/{id}", webConfig.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.id").value(webConfig.getId().intValue()))
            .andExpect(jsonPath("$.packages").value(DEFAULT_PACKAGES.toString()))
            .andExpect(jsonPath("$.assetsType").value(DEFAULT_ASSETS_TYPE))
            .andExpect(jsonPath("$.appSchema").value(DEFAULT_APP_SCHEMA.toString()));
    }


    @Test
    @Transactional
    public void getWebConfigsByIdFiltering() throws Exception {
        // Initialize the database
        webConfigRepository.saveAndFlush(webConfig);

        Long id = webConfig.getId();

        defaultWebConfigShouldBeFound("id.equals=" + id);
        defaultWebConfigShouldNotBeFound("id.notEquals=" + id);

        defaultWebConfigShouldBeFound("id.greaterThanOrEqual=" + id);
        defaultWebConfigShouldNotBeFound("id.greaterThan=" + id);

        defaultWebConfigShouldBeFound("id.lessThanOrEqual=" + id);
        defaultWebConfigShouldNotBeFound("id.lessThan=" + id);
    }


    @Test
    @Transactional
    public void getAllWebConfigsByAssetsTypeIsEqualToSomething() throws Exception {
        // Initialize the database
        webConfigRepository.saveAndFlush(webConfig);

        // Get all the webConfigList where assetsType equals to DEFAULT_ASSETS_TYPE
        defaultWebConfigShouldBeFound("assetsType.equals=" + DEFAULT_ASSETS_TYPE);

        // Get all the webConfigList where assetsType equals to UPDATED_ASSETS_TYPE
        defaultWebConfigShouldNotBeFound("assetsType.equals=" + UPDATED_ASSETS_TYPE);
    }

    @Test
    @Transactional
    public void getAllWebConfigsByAssetsTypeIsNotEqualToSomething() throws Exception {
        // Initialize the database
        webConfigRepository.saveAndFlush(webConfig);

        // Get all the webConfigList where assetsType not equals to DEFAULT_ASSETS_TYPE
        defaultWebConfigShouldNotBeFound("assetsType.notEquals=" + DEFAULT_ASSETS_TYPE);

        // Get all the webConfigList where assetsType not equals to UPDATED_ASSETS_TYPE
        defaultWebConfigShouldBeFound("assetsType.notEquals=" + UPDATED_ASSETS_TYPE);
    }

    @Test
    @Transactional
    public void getAllWebConfigsByAssetsTypeIsInShouldWork() throws Exception {
        // Initialize the database
        webConfigRepository.saveAndFlush(webConfig);

        // Get all the webConfigList where assetsType in DEFAULT_ASSETS_TYPE or UPDATED_ASSETS_TYPE
        defaultWebConfigShouldBeFound("assetsType.in=" + DEFAULT_ASSETS_TYPE + "," + UPDATED_ASSETS_TYPE);

        // Get all the webConfigList where assetsType equals to UPDATED_ASSETS_TYPE
        defaultWebConfigShouldNotBeFound("assetsType.in=" + UPDATED_ASSETS_TYPE);
    }

    @Test
    @Transactional
    public void getAllWebConfigsByAssetsTypeIsNullOrNotNull() throws Exception {
        // Initialize the database
        webConfigRepository.saveAndFlush(webConfig);

        // Get all the webConfigList where assetsType is not null
        defaultWebConfigShouldBeFound("assetsType.specified=true");

        // Get all the webConfigList where assetsType is null
        defaultWebConfigShouldNotBeFound("assetsType.specified=false");
    }
                @Test
    @Transactional
    public void getAllWebConfigsByAssetsTypeContainsSomething() throws Exception {
        // Initialize the database
        webConfigRepository.saveAndFlush(webConfig);

        // Get all the webConfigList where assetsType contains DEFAULT_ASSETS_TYPE
        defaultWebConfigShouldBeFound("assetsType.contains=" + DEFAULT_ASSETS_TYPE);

        // Get all the webConfigList where assetsType contains UPDATED_ASSETS_TYPE
        defaultWebConfigShouldNotBeFound("assetsType.contains=" + UPDATED_ASSETS_TYPE);
    }

    @Test
    @Transactional
    public void getAllWebConfigsByAssetsTypeNotContainsSomething() throws Exception {
        // Initialize the database
        webConfigRepository.saveAndFlush(webConfig);

        // Get all the webConfigList where assetsType does not contain DEFAULT_ASSETS_TYPE
        defaultWebConfigShouldNotBeFound("assetsType.doesNotContain=" + DEFAULT_ASSETS_TYPE);

        // Get all the webConfigList where assetsType does not contain UPDATED_ASSETS_TYPE
        defaultWebConfigShouldBeFound("assetsType.doesNotContain=" + UPDATED_ASSETS_TYPE);
    }


    @Test
    @Transactional
    public void getAllWebConfigsByAppClassIsEqualToSomething() throws Exception {
        // Initialize the database
        webConfigRepository.saveAndFlush(webConfig);
        AppClass appClass = AppClassResourceIT.createEntity(em);
        em.persist(appClass);
        em.flush();
        webConfig.setAppClass(appClass);
        appClass.setWebConfig(webConfig);
        webConfigRepository.saveAndFlush(webConfig);
        Long appClassId = appClass.getId();

        // Get all the webConfigList where appClass equals to appClassId
        defaultWebConfigShouldBeFound("appClassId.equals=" + appClassId);

        // Get all the webConfigList where appClass equals to appClassId + 1
        defaultWebConfigShouldNotBeFound("appClassId.equals=" + (appClassId + 1));
    }

    /**
     * Executes the search, and checks that the default entity is returned.
     */
    private void defaultWebConfigShouldBeFound(String filter) throws Exception {
        restWebConfigMockMvc.perform(get("/api/web-configs?sort=id,desc&" + filter))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(webConfig.getId().intValue())))
            .andExpect(jsonPath("$.[*].packages").value(hasItem(DEFAULT_PACKAGES.toString())))
            .andExpect(jsonPath("$.[*].assetsType").value(hasItem(DEFAULT_ASSETS_TYPE)))
            .andExpect(jsonPath("$.[*].appSchema").value(hasItem(DEFAULT_APP_SCHEMA.toString())));

        // Check, that the count call also returns 1
        restWebConfigMockMvc.perform(get("/api/web-configs/count?sort=id,desc&" + filter))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(content().string("1"));
    }

    /**
     * Executes the search, and checks that the default entity is not returned.
     */
    private void defaultWebConfigShouldNotBeFound(String filter) throws Exception {
        restWebConfigMockMvc.perform(get("/api/web-configs?sort=id,desc&" + filter))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$").isArray())
            .andExpect(jsonPath("$").isEmpty());

        // Check, that the count call also returns 0
        restWebConfigMockMvc.perform(get("/api/web-configs/count?sort=id,desc&" + filter))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(content().string("0"));
    }

    @Test
    @Transactional
    public void getNonExistingWebConfig() throws Exception {
        // Get the webConfig
        restWebConfigMockMvc.perform(get("/api/web-configs/{id}", Long.MAX_VALUE))
            .andExpect(status().isNotFound());
    }

    @Test
    @Transactional
    public void updateWebConfig() throws Exception {
        // Initialize the database
        webConfigRepository.saveAndFlush(webConfig);

        int databaseSizeBeforeUpdate = webConfigRepository.findAll().size();

        // Update the webConfig
        WebConfig updatedWebConfig = webConfigRepository.findById(webConfig.getId()).get();
        // Disconnect from session so that the updates on updatedWebConfig are not directly saved in db
        em.detach(updatedWebConfig);
        updatedWebConfig
            .packages(UPDATED_PACKAGES)
            .assetsType(UPDATED_ASSETS_TYPE)
            .appSchema(UPDATED_APP_SCHEMA);
        WebConfigDTO webConfigDTO = webConfigMapper.toDto(updatedWebConfig);

        restWebConfigMockMvc.perform(put("/api/web-configs").with(csrf())
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(webConfigDTO)))
            .andExpect(status().isOk());

        // Validate the WebConfig in the database
        List<WebConfig> webConfigList = webConfigRepository.findAll();
        assertThat(webConfigList).hasSize(databaseSizeBeforeUpdate);
        WebConfig testWebConfig = webConfigList.get(webConfigList.size() - 1);
        assertThat(testWebConfig.getPackages()).isEqualTo(UPDATED_PACKAGES);
        assertThat(testWebConfig.getAssetsType()).isEqualTo(UPDATED_ASSETS_TYPE);
        assertThat(testWebConfig.getAppSchema()).isEqualTo(UPDATED_APP_SCHEMA);
    }

    @Test
    @Transactional
    public void updateNonExistingWebConfig() throws Exception {
        int databaseSizeBeforeUpdate = webConfigRepository.findAll().size();

        // Create the WebConfig
        WebConfigDTO webConfigDTO = webConfigMapper.toDto(webConfig);

        // If the entity doesn't have an ID, it will throw BadRequestAlertException
        restWebConfigMockMvc.perform(put("/api/web-configs").with(csrf())
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(webConfigDTO)))
            .andExpect(status().isBadRequest());

        // Validate the WebConfig in the database
        List<WebConfig> webConfigList = webConfigRepository.findAll();
        assertThat(webConfigList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    public void deleteWebConfig() throws Exception {
        // Initialize the database
        webConfigRepository.saveAndFlush(webConfig);

        int databaseSizeBeforeDelete = webConfigRepository.findAll().size();

        // Delete the webConfig
        restWebConfigMockMvc.perform(delete("/api/web-configs/{id}", webConfig.getId()).with(csrf())
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isNoContent());

        // Validate the database contains one less item
        List<WebConfig> webConfigList = webConfigRepository.findAll();
        assertThat(webConfigList).hasSize(databaseSizeBeforeDelete - 1);
    }
}
